﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ReferralTracker.BusinessObjects;
using ReferralTracker.BusinessObjects.Infrastructure;
using ReferralTracker.Data.Entities;
using ReferralTracker.Helpers;
using ReferralTracker.Models.Api;
using System.Web.Configuration;
using System.Net.Http.Headers;
using ReferralTracker.Data.Lookups;

namespace ReferralTracker.ApiControllers {

    public class ReferralController : ApiController {

        public HttpResponseMessage PostReferral(ReferralPostModel model) {
            var session = ReferralTrackerSession.Open();
            var account = new AccountManagement();
            var user = account.GetUser(model.ReferralId);
            HttpResponseMessage response = null;

            if (user != null && IsUserValid(model)) {
                var transaction = new ReferralTransaction();
                var referral = new Referral() {
                    User = user,
                    IdReferralType = (ReferralType)model.ReferralType,
                    ReferralLink = model.ReferralLink,
                    ClientIPAddress = model.ClientIPAddress
                };

                transaction.AddReferral(referral);
                session.Commit();

                response = Request.CreateResponse<ReferralPostModel>(HttpStatusCode.Created, model);
                CreateCookie(response, model);
            }
            else {
                response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid Data Passed");
            }

            session.Close();

            return response;
        }

        private bool IsUserValid(ReferralPostModel model) {
            var isValid = true;

            if (isValid && string.IsNullOrEmpty(model.ReferralLink)) isValid = false;
            if (isValid && model.ReferralType <= 0) isValid = false;

            return isValid;
        }

        private void CreateCookie(HttpResponseMessage response, ReferralPostModel model) {
            var request = response.RequestMessage;
            var cookieName = WebConfigurationManager.AppSettings["CookieName"];
            var cookie = request.Headers.GetCookies(cookieName).FirstOrDefault();

            if (cookie == null) {
                var uri = new Uri(model.ReferralLink);
                var domain = uri.GetLeftPart(UriPartial.Authority);

                cookie = new CookieHeaderValue(cookieName, model.ReferralId) {
                    Expires = DateTime.Now.AddDays(30),
                    Path = "/"
                };

                response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
            }
        }
    }
}
